package system;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.concurrent.CountDownLatch;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

/**	The implementation for this class is taken more or less from the Branch.java
 * 	example provided.
 * 	@author David Illescas
 *
 */
@SuppressWarnings("serial")
public class 
LoginWindow 
extends JFrame
implements ActionListener, Runnable
{	private JTextField uname_field = new JTextField(10);
    private JPasswordField password_field = new JPasswordField(10);
    JLabel uname_label = new JLabel("Enter username: ");
	JLabel password_label = new JLabel("Enter password: ");
	JButton login_button = new JButton("Log In");
	JPanel content_pane = new JPanel();
	GridBagLayout grid_bag = new GridBagLayout();
    
    private int login_attempts = 0;
    // to put this thread to sleep until the user has finished inputting
    // login information
    private CountDownLatch latch = new CountDownLatch(1);
	private View view = null;

    public
    LoginWindow(View v){ view  = v; }
    
    private void 
    setUpLoginWindow() 
    {	setTitle("Login Window");     	
    	setContentPane(content_pane);
    	
    	pack();        
        
    	// center the frame
        Dimension d = getToolkit().getScreenSize();
        Rectangle r = getBounds();
        setLocation( (d.width - r.width)/2, (d.height - r.height)/2 );
        
        setVisible(true);
	}

	private void 
	setListeners() 
	{	login_button.addActionListener(this);
        password_field.addActionListener(this);
        addWindowListener(new WindowAdapter() 
        {	public void windowClosing(WindowEvent e) {	System.exit(0); }
        	public void windowClosed(WindowEvent e)
        	{	view.registerControllers(); 
        		System.out.println("Logged in Successfully.");
        		SQLScriptRunner s = new SQLScriptRunner("project.sql");
        		s.execute();
        	}
        });
	}

	private void 
    buildContentPane() 
    {	GridBagConstraints c = new GridBagConstraints();
    	
    	content_pane.setLayout(grid_bag);
        content_pane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        
        // place the username label 
        c.gridwidth = GridBagConstraints.RELATIVE;
        c.insets = new Insets(10, 10, 5, 0);
        grid_bag.setConstraints(uname_label, c);
        content_pane.add(uname_label);
        
    	// place the text field for the username 
        c.gridwidth = GridBagConstraints.REMAINDER;
        c.insets = new Insets(10, 0, 5, 10);
        grid_bag.setConstraints(uname_field, c);
        content_pane.add(uname_field);

        // place password label
        c.gridwidth = GridBagConstraints.RELATIVE;
        c.insets = new Insets(0, 10, 10, 0);
        grid_bag.setConstraints(password_label, c);
        content_pane.add(password_label);

        // place the password field 
        c.gridwidth = GridBagConstraints.REMAINDER;
        c.insets = new Insets(0, 0, 10, 10);
        grid_bag.setConstraints(password_field, c);
        content_pane.add(password_field);

        // place the login button
        c.gridwidth = GridBagConstraints.REMAINDER;
        c.insets = new Insets(5, 10, 10, 10);
        c.anchor = GridBagConstraints.CENTER;
        grid_bag.setConstraints(login_button, c);
        content_pane.add(login_button);
        
        uname_field.requestFocus();
        password_field.setEchoChar('*');
	}

	@Override
	public void 
	actionPerformed(ActionEvent e){	
		if(	OracleConnection.getInstance().connect(
				uname_field.getText(), 
				String.valueOf(password_field.getPassword())
			)
		){	dispose();
			latch.countDown();
		} else {	
			JOptionPane.showMessageDialog(this, "Incorrect Username/Password Combination \n"+(2-login_attempts)+" login attempts remaining.", "Error", JOptionPane.ERROR_MESSAGE);
			System.err.println("Failed to Login: " +(2 - login_attempts) + " attempt(s) remaining.");
			login_attempts++;
		  	if (login_attempts >= 3) {	
		  		dispose();
		  		System.err.println(
		  			"\nFailed to Login Successfully.\n"+
		  			"Terminating Application.");
		  		System.exit(-1);
		  	} else password_field.setText("");
		}         
	}
	
	@Override
	public void 
	run() 
	{	buildContentPane();
        setListeners();        
        setUpLoginWindow();
       
        try { latch.await(); } 
        catch (InterruptedException e) { e.printStackTrace(); }
	}
}